# -*- coding: utf-8 -*-
class LoanController < ApplicationController
  before_filter :employee_authorize
  before_filter :sys_before_log
  before_filter :employee_action_hx
  before_filter :privilege_filter,:except=>[:newLoan,:editLoan,:editLoanAfterAudit,:auditLoanForEdit,:auditLoanForCancel,:hxListForLoan,:editloanAfterAudit,:hxListForSale,:loanForReturnedList,:deliveryForLoanList,:loan_print_content,:loan_print_header,:loan_print_footer]
  
  def loanList
    
  end

  def loanAuditList
    
  end

  #可出库借货订单
  def loanForDeliveryList
    
  end

  #可返库借货订单
  def loanForReturnedList
    
  end
  
  def getAllLoans
    begin
      conditionsHash = Hash.new
      paramsHash = Hash.new
      paramsHash[:offset] = params[:start].to_i
      paramsHash[:limit] = params[:limit].to_i

      conditionsStr = ''

      if params[:order_number].to_s != ''
        conditionsStr = 'seq_number in (:order_number)'
        conditionsHash[:order_number] = params[:order_number].split(/,/)
      end

      if params[:auditing_status].to_s != '' && params[:auditing_status] != ' '
        if conditionsStr == ''
          conditionsStr = 'auditing_status like :auditing_status'
        else
          conditionsStr = conditionsStr+' AND auditing_status like :auditing_status'
        end
        conditionsHash[:auditing_status] = '%'+params[:auditing_status].to_s+'%'
      elsif params[:auditing_status] == ' '
        if conditionsStr == ''
          conditionsStr = 'auditing_status = :auditing_status'
        else
          conditionsStr = conditionsStr+' AND auditing_status = :auditing_status'
        end
        conditionsHash[:auditing_status] = ''
      end

      if params[:customer_id].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'customer_id = :customer_id'
        else
          conditionsStr = conditionsStr+' AND customer_id = :customer_id'
        end
        conditionsHash[:customer_id] = params[:customer_id].to_i
      end

      #借货员
      if params[:sales_id].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'sales_id = :sales_id'
        else
          conditionsStr = conditionsStr+' AND sales_id = :sales_id'
        end
        conditionsHash[:sales_id] = params[:sales_id].to_i
      end

      if params[:begin_date].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'action_date >= :begin_date'
        else
          conditionsStr = conditionsStr+' AND action_date >= :begin_date'
        end
        conditionsHash[:begin_date] = params[:begin_date].to_date
      end

      if params[:end_date].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'action_date <= :end_date'
        else
          conditionsStr = conditionsStr+' AND action_date <= :end_date'
        end
        conditionsHash[:end_date] = params[:end_date].to_date
      end

      #显示产品
      if params[:product_id].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'loan_details.product_id = :product_id'
        else
          conditionsStr = conditionsStr+' AND loan_details.product_id = :product_id'
        end
        conditionsHash[:product_id] = params[:product_id].to_i
      end

      if params[:department_id].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'department_id = :department_id'
        else
          conditionsStr = conditionsStr+' AND department_id = :department_id'
        end
        conditionsHash[:department_id] = params[:department_id].to_i
      end

      count = Loan.countAllLoans conditionsStr,conditionsHash
      loans = Loan.findAllLoans conditionsStr,conditionsHash,paramsHash
      
      jsonStr="{totalProperty:"+count.to_s+",root:"+loans.to_json(:include=>[:employee,:department,:customer,:auditor,:sales])+"}"
      logger.info jsonStr
      render :text=>jsonStr, :layout=>false
    rescue Exception => e
      logger.info e
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
    end
  end

  #得到所有可返库的借货订单
  def getAllLoansForReturned
    begin
      conditionsHash = Hash.new
      paramsHash = Hash.new
      paramsHash[:offset] = params[:start].to_i
      paramsHash[:limit] = params[:limit].to_i

      conditionsStr = '(auditing_status like :auditing_status1 AND auditing_status not like :auditing_status2) '
      #在这儿补充一些可以入库的必要条件，比如不能是已经撤消的或申请撤消的。也不能是暂存的。
      conditionsHash[:auditing_status1] = "%通过%"
      conditionsHash[:auditing_status2] = "%撤消%"

      if params[:order_number].to_s != ''
        conditionsStr = ' AND seq_number in (:order_number)'
        conditionsHash[:order_number] = params[:order_number].split(/,/)
      end

      if params[:auditing_status].to_s != '' && params[:auditing_status] != ' '
        if conditionsStr == ''
          conditionsStr = 'auditing_status like :auditing_status'
        else
          conditionsStr = conditionsStr+' AND auditing_status like :auditing_status'
        end
        conditionsHash[:auditing_status] = '%'+params[:auditing_status].to_s+'%'
      elsif params[:auditing_status] == ' '
        if conditionsStr == ''
          conditionsStr = 'auditing_status = :auditing_status'
        else
          conditionsStr = conditionsStr+' AND auditing_status = :auditing_status'
        end
        conditionsHash[:auditing_status] = ''
      end

      if params[:customer_id].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'customer_id = :customer_id'
        else
          conditionsStr = conditionsStr+' AND customer_id = :customer_id'
        end
        conditionsHash[:customer_id] = params[:customer_id].to_i
      end

      #借货员
      if params[:sales_id].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'sales_id = :sales_id'
        else
          conditionsStr = conditionsStr+' AND sales_id = :sales_id'
        end
        conditionsHash[:sales_id] = params[:sales_id].to_i
      end

      if params[:begin_date].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'action_date >= :begin_date'
        else
          conditionsStr = conditionsStr+' AND action_date >= :begin_date'
        end
        conditionsHash[:begin_date] = params[:begin_date].to_date
      end

      if params[:end_date].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'action_date <= :end_date'
        else
          conditionsStr = conditionsStr+' AND action_date <= :end_date'
        end
        conditionsHash[:end_date] = params[:end_date].to_date
      end

      #显示产品
      if params[:product_id].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'loan_details.product_id = :product_id'
        else
          conditionsStr = conditionsStr+' AND loan_details.product_id = :product_id'
        end
        conditionsHash[:product_id] = params[:product_id].to_i
      end

      if params[:department_id].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'department_id = :department_id'
        else
          conditionsStr = conditionsStr+' AND department_id = :department_id'
        end
        conditionsHash[:department_id] = params[:department_id].to_i
      end

      count = Loan.countAllLoans conditionsStr,conditionsHash
      loans = Loan.findAllLoans conditionsStr,conditionsHash,paramsHash

      jsonStr="{totalProperty:"+count.to_s+",root:"+loans.to_json(:include=>[:employee,:department,:customer,:auditor,:sales])+"}"
      logger.info jsonStr
      render :text=>jsonStr, :layout=>false
    rescue Exception => e
      logger.info e
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
    end
  end
  
  def getLoanById
    loan = Loan.find(params[:id],:include=>[:customer,:sales])
    rootStr = loan.to_json(:include=>[:customer,:sales])
    jsonStr = "{root:["+rootStr+"]}"
    render :text=>jsonStr, :layout=>false
  end

  def getLoanDetailsById
    loanDetails = LoanDetail.find_all_by_loan_id(params[:loan_id],:include=>[:product],:conditions=>['is_locked = 0'])
    jsonStr="{totalProperty:"+loanDetails.length.to_s+",root:"+loanDetails.to_json(:include=>{:product=>{:only=>[:id,:name,:is_suit,:spec,:number,:unit]}})+"}"
    logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #得到被锁定的借货订单详细项
  def getLockedLoanDetailsById
    loanDetails = LoanDetail.find_all_by_loan_id(params[:loan_id],:include=>[:product],:conditions=>['is_locked = 1'])
    jsonStr="{totalProperty:"+loanDetails.length.to_s+",root:"+loanDetails.to_json(:include=>{:product=>{:only=>[:id,:name,:is_suit,:spec]}})+"}"
    logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  def getAllLoansByAuditStatus
    conditionsHash = Hash.new
    paramsHash = Hash.new
    paramsHash[:offset] = params[:start].to_i
    paramsHash[:limit] = params[:limit].to_i
    conditionsStr = ''

    if params[:order_number].to_s != ''
      conditionsStr = 'seq_number in (:order_number)'
      conditionsHash[:order_number] = params[:order_number].split(/,/)
    end

    #这里要把暂存的订单排除在外。默认只选择“申请”状态的
    if params[:auditing_status].nil? || params[:auditing_status] == ""
      if conditionsStr == ''
        conditionsStr = "auditing_status like :auditing_status"
      else
        conditionsStr = conditionsStr + " AND auditing_status like :auditing_status"
      end
      conditionsHash[:auditing_status] = "%#{Constants::APPLY}%"
    else
      if conditionsStr == ''
        conditionsStr = "auditing_status like :auditing_status"
      else
        conditionsStr = conditionsStr + " AND auditing_status like :auditing_status"
      end
      conditionsHash[:auditing_status] = '%'+params[:auditing_status].to_s+'%'
    end

    if params[:customer_id].to_s != ''
      if conditionsStr == ''
        conditionsStr = 'customer_id = :customer_id'
      else
        conditionsStr = conditionsStr+' AND customer_id = :customer_id'
      end
      conditionsHash[:customer_id] = params[:customer_id].to_i
    end

    if params[:begin_date].to_s != ''
      if conditionsStr == ''
        conditionsStr = 'action_date >= :begin_date'
      else
        conditionsStr = conditionsStr+' AND action_date >= :begin_date'
      end
      conditionsHash[:begin_date] = params[:begin_date].to_date
    end

    if params[:end_date].to_s != ''
      if conditionsStr == ''
        conditionsStr = 'action_date <= :end_date'
      else
        conditionsStr = conditionsStr+' AND action_date <= :end_date'
      end
      conditionsHash[:end_date] = params[:end_date].to_date
    end

    count = Loan.countAllLoans conditionsStr,conditionsHash
    loans = Loan.findAllLoans conditionsStr,conditionsHash,paramsHash

    jsonStr="{totalProperty:"+count.to_s+",root:"+loans.to_json(:include=>[:employee,:department,:customer,:auditor])+"}"
    logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #更新审批状态
  def updateAuditingStatus
    
  end

  #创建新的借货订单。
  def create
    paramsHash = Util.paramsPreprocesseToHash(params[:data])
    #productHash = paramsHash["products"][0]

    loan = Loan.new
    loan.company_id = session[:company_id]
    loan.department_id = session[:department_id]
    loan.employee_id = session[:employee_id]
    loan.customer_id = paramsHash['customer_id']
    loan.linkman = paramsHash['linkman']
    loan.phone = paramsHash['phone']
    loan.sales_id = paramsHash['sales_id']
    #现在不知原因sales_id可能为空
    logger.info "现在不知原因sales_id可能为空"
    logger.info paramsHash['sales_id']
    loan.delivery_address = paramsHash['delivery_address']
    loan.contract_number = paramsHash['contract_number']
    loan.action_date = paramsHash['action_date']
    loan.description = paramsHash['description']

    #判断一下当前用户角色是否需求审批
    sysParam =  SysParam.find_by_company_id(session[:company_id])

    #判断是暂存还是提交,结合审批一起处理，如果是暂存，就不处理审批的情形
    if paramsHash['temporary'] == '1'
      loan.deal_with_status = Constants::TEMP_ADD
    else
      if sysParam.audit_for_loan_add == "否"
        loan.auditing_status = Constants::PASS_APPLY_ADD
        loan.deal_with_status = ''
      else
        loan.auditing_status = Constants::AUDIT_APPLY_ADD
      end
    end

    #插入products信息
    productsHashArray = paramsHash["products"]
    productsHashArray.each do |productHash|
      #如果不为空则加入
      if productHash["product_id"] !=""
        loadDetail = LoanDetail.new
        loadDetail.product_id = productHash["product_id"]
        loadDetail.quantity = productHash["quantity"]
        loadDetail.description = productHash["description"]
        loan.loan_details << loadDetail
      end
    end

    #开始事务，确保在流水号正常的情况下，保存借货订单,一但出现问题，则循环执行
    begin
      Sequence.transaction do
        #开始为借货订单取得流水号
        sequence = Sequence.find(:first,:conditions=>["company_id = ? AND sub_type = ?",session[:company_id],Loan.name])

        sequence.seq_no = sequence.seq_no + 1
        loan.seq_number = sequence.seq_no
        loan.order_number = sequence.ab + ":" + loan.seq_number.to_s + ":" + Date.today.to_s
        sequence.save!
        loan.save!
      end
    rescue ActiveRecord::StaleObjectError
      #这个异常是说明，你当提交时，有人提前更新了你之前读取的信息，违反乐观锁。要retry
      #这里特别指序号产生表。
      logger.info "somebody using sn before yours.............................................................."
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,"StaleObjectError")
      retry
    rescue ActiveRecord::RecordNotFound
      logger.info "RecordNotFound................................................................................"
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,"RecordNotFound")
    rescue Exception => e
      logger.info "logging......................................................................................."
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
      logger.info e
    end

    info="成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #编辑后的保存
  def update
    paramsHash = Util.paramsPreprocesseToHash(params[:data])
    #productHash = paramsHash["products"][0]
    loan = Loan.find(:first,:conditions=>["id = ? AND company_id = ? AND is_locked <> 1 AND (auditing_status is null OR auditing_status not like ?)",paramsHash['id'],session[:company_id],'%通过%'])
    if loan != nil
      if loan.lock_version > paramsHash['lock_version'].to_i
        info="有其它用户在您保存之前编辑过此借货订单记录，请从新编辑！"
        result = "{success:true,info:'#{info}'}"
        render :text=>result, :layout=>false and return false
      end
      
      loan.company_id = session[:company_id]
      loan.department_id = session[:department_id]
      loan.employee_id = session[:employee_id]
      loan.customer_id = paramsHash['customer_id']
      loan.linkman = paramsHash['linkman']
      loan.phone = paramsHash['phone']
      loan.sales_id = paramsHash['sales_id']
      loan.delivery_address = paramsHash['delivery_address']
      loan.contract_number = paramsHash['contract_number']
      loan.action_date = paramsHash['action_date']
      loan.description = paramsHash['description']

      loan.audit_opinion = ''
      loan.auditor_id = ''

      #判断一下当前用户角色是否需求审批
      sysParam =  SysParam.find_by_company_id(session[:company_id])

      #判断是暂存还是提交,结合审批一起处理，如果是暂存，就不处理审批的情形
      if paramsHash['temporary'] == '1'
        loan.deal_with_status = Constants::TEMP_ADD
      else
        if sysParam.audit_for_loan_add == "否"
          loan.auditing_status = Constants::PASS_APPLY_ADD
          loan.deal_with_status = ''
        else
          loan.auditing_status = Constants::AUDIT_APPLY_ADD
        end
      end

      #products信息
      productsHashArray = paramsHash["products"]
      #在这里，要作一个增，删，编辑操作，以前台数据为准。
      #首先各取出前台与后台的ID数组
      fgIdArray = Array.new
      productsHashArray.each do |productHash|
        fgIdArray << productHash["id"].to_i
      end

      bgIdArray = Array.new
      loanDetails = loan.loan_details
      loanDetails.each do |loanDetail|
        bgIdArray << loanDetail.id
      end

      idIntersectionArray = fgIdArray & bgIdArray
      addIdArray = fgIdArray - idIntersectionArray
      delIdArray = bgIdArray - idIntersectionArray
      LoanDetail.delete(delIdArray)

      #在进行从新整理数据之前，先把借货订单的总金额置“0”
      loan.amount = 0

      productsHashArray.each do |productHash|
        #只有当用户选择的产品不为空时，才有详细订单。
        if productHash["product_id"] !=""
          #没Id说明是新增加的。
          if productHash["id"] == ""
            loanDetail = LoanDetail.new
            loanDetail.product_id = productHash["product_id"]
            loanDetail.quantity = productHash["quantity"]
            loan.amount = loan.amount + loanDetail.amount #计算订单总金额
            loanDetail.description = productHash["description"]
            loan.loan_details << loanDetail
          else
            loanDetail = LoanDetail.find(productHash["id"].to_i)
            loanDetail.product_id = productHash["product_id"]
            loanDetail.quantity = productHash["quantity"]
            loan.amount = loan.amount + loanDetail.amount #计算订单总金额
            loanDetail.description = productHash["description"]
            loanDetail.save
          end
        end
      end
      loan.save
    end

    info="成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #当销售订单在通过审批后，又一次编辑基本信息时，用此方法。此方法可以不经过审批
  def updateBaseInfoAfterAudit
    #productHash = paramsHash["products"][0]

    loan = Loan.find(:first,:conditions=>["id = ? AND company_id = ? AND is_locked <> 1 AND (auditing_status is null OR auditing_status not like ?)",params[:id],session[:company_id],'%撤消%'])

    #如果在保存时，有人编辑过，则不能保证
    if loan.lock_version > params[:lock_version].to_i
      info="有其它用户在您保存之前编辑过此借货订单记录，请从新编辑！"
      result = "{success:true,info:'#{info}'}"
      render :text=>result, :layout=>false and return false
    end

    loan.company_id = session[:company_id]
    loan.department_id = session[:department_id]
    loan.employee_id = session[:employee_id]
    loan.customer_id = params[:customer_id]
    loan.linkman = params[:linkman]
    loan.phone = params[:phone]
    loan.sales_id = params[:sales_id]
    loan.delivery_address = params[:delivery_address]
    loan.contract_number = params[:contract_number]
    loan.action_date = params[:action_date]
    loan.description = params[:description]

    #saleOrder.save

    #开始事务，确保在流水号正常的情况下，保存销售订单,一但出现问题，则循环执行
    begin
      Sequence.transaction do
        loan.save!
      end
    rescue ActiveRecord::StaleObjectError
      #这个异常是说明，你当提交时，有人提前更新了你之前读取的信息，违反乐观锁。要retry
      #这里特别指序号产生表。
      logger.info "somebody using sn before yours.............................................................."
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,"StaleObjectError")
      retry
    rescue ActiveRecord::RecordNotFound
      logger.info "RecordNotFound................................................................................"
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,"RecordNotFound")
    rescue Exception => e
      logger.info "logging......................................................................................."
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
      logger.info e
    end

    info="成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end
  
  #查询借货订单，合呼要求的，可以转化为出库单。
  def getAllLoansForDelivery
    conditionsHash = Hash.new
    paramsHash = Hash.new
    paramsHash[:offset] = params[:start].to_i
    paramsHash[:limit] = params[:limit].to_i

    conditionsStr = '(auditing_status not like :auditing_status1 AND auditing_status not like :auditing_status2) '
    #在这儿补充一些可以入库的必要条件，比如不能是已经撤消的或申请撤消的。也不能是暂存的。
    conditionsHash[:auditing_status1] = "%#{Constants::APPLY}%"
    conditionsHash[:auditing_status2] = "%#{Constants::PASS_APPLY_CANCEL}%"

    if params[:order_number].to_s != ''
      conditionsStr = conditionsStr + ' AND seq_number in (:order_number)'
      conditionsHash[:order_number] = params[:order_number].split(/,/)
    end


    if params[:auditing_status].to_s != '' && params[:auditing_status] != ' '
      conditionsStr = conditionsStr + ' AND auditing_status like :auditing_status'
      conditionsHash[:auditing_status] = '%'+params[:auditing_status].to_s+'%'
    elsif params[:auditing_status] == ' '
      conditionsStr = conditionsStr + ' AND auditing_status = :auditing_status'
      conditionsHash[:auditing_status] = ' '
    end
      

    if params[:customer_id].to_s != ''
      conditionsStr = conditionsStr + ' AND customer_id = :customer_id'
      conditionsHash[:customer_id] = params[:customer_id].to_i
    end

    if params[:begin_date].to_s != ''
      conditionsStr = conditionsStr + ' AND action_date >= :begin_date'
      conditionsHash[:begin_date] = params[:begin_date].to_date
    end

    if params[:end_date].to_s != ''
      conditionsStr = conditionsStr + ' AND action_date <= :end_date'
      conditionsHash[:end_date] = params[:end_date].to_date
    end

    count = Loan.countAllLoans conditionsStr,conditionsHash
    loans = Loan.findAllLoans conditionsStr,conditionsHash,paramsHash

    jsonStr="{totalProperty:"+count.to_s+",root:"+loans.to_json(:include=>[:employee,:department,:customer,:auditor])+"}"
    logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end
  
  def getLoanDetailBalanceForDelivery
    loanId = params[:loan_id]
    #order_quantity是未转的数量，不代表可以转，因为有时候库存不足
    #总的思路就是显示可前本销售订单可转数，
    productIds = Array.new
    loanDetails = LoanDetail.find(:all,:conditions=>["loan_id = ? AND is_locked = 0",loanId])
    loanDetails.each do |loanDetail|
      productIds << loanDetail.product_id
    end
    loans = Loan.find(:all,:select=>"ld.id,p.id as product_id,p.name as product_name,p.is_suit,p.unit_price,p.number,p.spec,p.unit,ld.quantity,ld.description,ld.quantity - ifnull(newdd.quantity,0) as order_quantity,case when ld.quantity - ifnull(newdd.quantity,0) > ifnull(pc.stock_quantity,0) - ifnull(newdd.quantity,0) then ifnull(pc.stock_quantity,0) - ifnull(newdd.quantity,0) else ld.quantity - ifnull(newdd.quantity,0) END as balance_quantity,ifnull(pc.stock_quantity,0) as stock_quantity ",:joins =>"l
left join loan_details ld on l.id = ld.loan_id
left join (select loan_delivery_id,d.loan_id,product_id,sum(quantity) as quantity
from loan_deliveries d left join loan_delivery_details dd on d.id = dd.loan_delivery_id
where d.loan_id = "+loanId+" AND d.auditing_status != '#{Constants::PASS_APPLY_CANCEL}'
group by product_id) newdd on newdd.product_id = ld.product_id
left join products p on p.id = ld.product_id
left join (select product_id,sum(quantity) as stock_quantity from product_collections where is_locked = 0 AND product_id in (#{productIds.join(",")}) group by product_id) pc on pc.product_id = p.id
where (ld.quantity - ifnull(newdd.quantity,0)) > 0 AND l.id =  "+loanId)

    jsonStr="{totalProperty:"+loans.length.to_s+",root:"+loans.to_json()+"}"
    logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #得到某借货订单的详细信息，并显示与出库单之间的数量差比
  def getLoanDetailsBalanceById
    loanId = params[:loan_id]
    loans = Loan.find(:all,:select=>"ld.id,p.id as product_id,p.name as product_name,p.number as product_number,p.is_suit,p.number,p.spec,p.unit,ld.quantity,ld.description,newdd.quantity as dd_quantity,(ifnull(newdd.quantity,0) - ld.quantity) as balance_quantity ",:joins =>"l
left join loan_details ld on l.id = ld.loan_id AND ld.is_locked = 0
left join (select loan_delivery_id,ld.loan_id,product_id,sum(quantity) as quantity
from loan_deliveries ld left join loan_delivery_details dd on ld.id = dd.loan_delivery_id
where ld.loan_id = "+loanId+" AND ld.auditing_status != '#{Constants::PASS_APPLY_CANCEL}'
group by product_id) newdd on newdd.product_id = ld.product_id
left join products p on p.id = ld.product_id
where l.id =  "+loanId)
    jsonStr="{totalProperty:"+loans.length.to_s+",root:"+loans.to_json()+"}"
    logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #对于借货订单是一定要通过审批的
  def applyToCancel
    loan = Loan.find(params[:id])

    if (loan.auditing_status.include? "通过") || (loan.auditing_status.include? "驳回")
      loan.auditing_status = Constants::AUDIT_APPLY_CANCEL
      loan.deal_with_status = Constants::AUDIT_APPLY_CANCEL
      #通过状态，要经过审批
    else
      #申请状态，可以直接标记为撤消
      loan.auditing_status = Constants::PASS_APPLY_CANCEL
      loan.deal_with_status = Constants::CANCELED
    end
    loan.auditor_id = session[:employee_id]
    loan.save!

    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #根据审批的结果，处理借货订单，如果审批同意，则取消所有入库单。
  def updateAuditingCancelStatus
    loan = Loan.find(params[:id])
    if params[:auditing_status]=='是'
      loan.auditing_status = Constants::PASS_APPLY_CANCEL
      loan.deal_with_status = Constants::CANCELED
      loan.audit_opinion = params[:audit_opinion]
    else
      loan.audit_opinion = params[:audit_opinion]
      loan.auditing_status = Constants::REJECT_APPLY_CANCEL
    end
    loan.auditor_id = session[:employee_id]
    loan.save!

    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #当借货订单在通过审批后，又一次编辑时，用此方法。
  def updateAfterAudit
    paramsHash = Util.paramsPreprocesseToHash(params[:data])
    #productHash = paramsHash["products"][0]
    #在这儿，只要能查看到此订单的人，就可以编辑，所以暂时去掉了员工Id的处理。
    loan = Loan.find(:first,:conditions=>["id = ? AND company_id = ? AND is_locked <> 1 AND (auditing_status is null OR auditing_status not like ?)",paramsHash['id'],session[:company_id],'%撤消%'])

    if loan.lock_version > paramsHash['lock_version'].to_i
      info="有其它用户在您保存之前编辑过此借货订单记录，请从新编辑！"
      result = "{success:true,info:'#{info}'}"
      render :text=>result, :layout=>false and return false
    end
      
    loan.company_id = session[:company_id]
    loan.department_id = session[:department_id]
    loan.employee_id = session[:employee_id]
    loan.customer_id = paramsHash['customer_id']
    loan.linkman = paramsHash['linkman']
    loan.phone = paramsHash['phone']
    loan.sales_id = paramsHash['sales_id']
    loan.delivery_address = paramsHash['delivery_address']
    loan.contract_number = paramsHash['contract_number']
    loan.action_date = paramsHash['action_date']
    loan.description = paramsHash['description']

    #判断一下当前用户角色是否需求审批
    sysParam =  SysParam.find_by_company_id(session[:company_id])

    #判断是暂存还是提交,结合审批一起处理，如果是暂存，就不处理审批的情形

    loan.auditing_status = Constants::AUDIT_APPLY_EDIT
    loan.deal_with_status = ''

    #插入products信息
    productsHashArray = paramsHash["products"]
    productsHashArray.each do |productHash|
      #如果不为空则加入
      if productHash["product_id"] !=""
        loanDetail = LoanDetail.new
        loanDetail.product_id = productHash["product_id"]
        loanDetail.quantity = productHash["quantity"]
        loanDetail.description = productHash["description"]
        loanDetail.is_locked = 1  #这里状态全是锁定的。
        loan.loan_details << loanDetail
      end
    end

    #loan.save

    #开始事务，确保在流水号正常的情况下，保存借货订单,一但出现问题，则循环执行
    begin
      Sequence.transaction do
        loan.save!
      end
    rescue ActiveRecord::StaleObjectError
      #这个异常是说明，你当提交时，有人提前更新了你之前读取的信息，违反乐观锁。要retry
      #这里特别指序号产生表。
      logger.info "somebody using sn before yours.............................................................."
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,"StaleObjectError")
      retry
    rescue ActiveRecord::RecordNotFound
      logger.info "RecordNotFound................................................................................"
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,"RecordNotFound")
    rescue Exception => e
      logger.info "logging......................................................................................."
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
      logger.info e
    end

    info="成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #审批申请变更的借货订单
  def updateAuditingEditStatus
    loan = Loan.find(params[:id])
    Loan.transaction do
      if params[:auditing_status]=='是'
        loanHx = LoanHx.new
        loanHx.loan_id = loan.id
        loanHx.company_id = session[:company_id]
        loanHx.department_id = session[:department_id]
        loanHx.employee_id = session[:employee_id]
        loanHx.customer_id = loan.customer_id
        loanHx.action_date = loan.action_date
        loanHx.sales_id = loan.sales_id
        loanHx.save!

        loan.auditing_status = Constants::PASS_APPLY_EDIT
        loan.deal_with_status = "已变更"
        loan.audit_opinion = params[:audit_opinion]

        oriIdArray = Array.new
        oriLoanDetails = loan.loan_details.where(:is_locked=>0)
        oriLoanDetails.each do |loanDetail|
          oriIdArray << loanDetail.product_id
          #在生成oriIdArray的同时进行旧有订单的历史备份
          loanHxDetail = LoanHxDetail.new
          loanHxDetail.loan_hx_id = loanHx.id
          loanHxDetail.product_id = loanDetail.product_id
          loanHxDetail.quantity = loanDetail.quantity
          loanHxDetail.description = loanDetail.description
          loanHxDetail.save!
        end

        newIdArray = Array.new
        newLoanDetails = loan.loan_details.where(:is_locked=>1)
        newLoanDetails.each do |loanDetail|
          newIdArray << loanDetail.product_id
        end

        idIntersectionArray = oriIdArray & newIdArray
        addIdArray = newIdArray - idIntersectionArray
        delIdArray = oriIdArray - idIntersectionArray
        if !delIdArray.empty?
          LoanDetail.delete_all(["product_id in (?) AND loan_id = ?" , delIdArray,loan.id])
        end

        #把新增的记录，变为正式记录
        if !addIdArray.empty?
          LoanDetail.update_all("is_locked = 0","is_locked = 1 AND loan_id = #{loan.id} AND product_id in (#{addIdArray.join(',')})")
        end
        #LoanDetail.delete(delIdArray)
        #开始把新的产品的信息，添加到老的产品信息中。
        newLoanDetails.each do |newLoanDetail|
          oriLoanDetail = LoanDetail.find(:first,:conditions=>["loan_id = ? AND is_locked = 0 AND product_id = ?",loan.id,newLoanDetail.product_id])
          oriLoanDetail.quantity = newLoanDetail.quantity
          oriLoanDetail.description = newLoanDetail.description
          oriLoanDetail.save
        end
        loan.loan_details.where(:is_locked=>1).destroy_all
      else
        loan.audit_opinion = params[:audit_opinion]
        loan.loan_details.where(:is_locked=>1).destroy_all
        loan.auditing_status = Constants::REJECT_APPLY_EDIT
      end
      loan.auditor_id = session[:employee_id]
      loan.save!
    end
    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end
  
  #得到变更历史的摘要
  def getHxesById
    loanHxes = LoanHx.find_all_by_loan_id(params[:id],:include=>[:department,:employee])
    jsonStr="{totalProperty:"+loanHxes.length.to_s+",root:"+loanHxes.to_json(:include=>[:department,:employee])+"}"
    logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #根据变更Id得到详细信息
  def getHxDetailsByHxId
    loanHxDetails = LoanHxDetail.find_all_by_loan_hx_id(params[:id],:include=>[:product])
    jsonStr="{totalProperty:"+loanHxDetails.length.to_s+",root:"+loanHxDetails.to_json(:include=>{:product=>{:only=>[:id,:name,:is_suit,:spec]}})+"}"
    logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #生成打印销售凭证的头部
  def loan_print_header
    @loan = Loan.find(params[:id],:include=>[:department,:sales,:customer])

  end

  #生成打印销售凭证的内容
  def loan_print_content
    @loan = Loan.find(params[:id],:include=>[:loan_details,:sales,:customer])
    @loanDetails = @loan.loan_details
    @totalQuantity = @loanDetails.sum(:quantity)
    logger.info @totalQuantity
  end

  def loan_print_footer
    @loan = Loan.find(params[:id],:include=>[:loan_details,:sales,:customer])
  end
end
